<!--
 * @Author: 黄达全
 * @Date: 2024-08-18 10:19:45
 * @LastEditTime: 2024-08-18 10:40:29
-->
<template>
  <div class="dynamic-tag">
    <el-tag v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false" @close="handleClose(tag)">
      {{ tag }}
    </el-tag>
    <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="tag-input" size="small"
      @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
    <el-button v-else class="button-new-tag" size="small" @click="showInput">
      + 添加
    </el-button>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, watch, onMounted } from 'vue'
import { ElInput } from 'element-plus'

const inputValue = ref<string>('')
const dynamicTags = ref<string[]>([])
const inputVisible = ref<boolean>(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
const props = defineProps<{
  tags: string
}>()
watch(() => props.tags, (newVal: string) => {
  console.log(newVal);
  dynamicTags.value = newVal.split(",")
})
onMounted(() => {
  dynamicTags.value = props.tags.split(",")
})


const emits = defineEmits(["update:modelValue"])

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
  emits("update:modelValue", dynamicTags.value.join(","))
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
  emits("update:modelValue", dynamicTags.value.join(","))
}
</script>

<style scoped>
.dynamic-tag {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  .tag-input {
    width: 80px;
  }
}
</style>